<template>
  <div>
    <!-- 对话框 -->
    <el-card shadow="hover" style="margin: auto;">
      <div style="height: 700px; overflow-y: auto; border: 1px solid #ddd; padding: 10px;">
        <!-- 历史消息 -->
        <div v-for="(msg, index) in messages" :key="index" style="margin-bottom: 8px;">
          <b v-if="msg.role === 'user'" style="color: #409EFF;">我：</b>
          <b v-else style="color: #67C23A;">AI：</b>
          <div class="markdown-body" v-html="renderMarkdown(msg.content)"></div>
        </div>

        <!-- AI 正在生成 -->
        <div v-if="loading" style="color: #aaa;">
          <b>AI 正在回答：</b>
          <div class="markdown-body" v-html="renderMarkdown(streamingContent)"></div>
        </div>
      </div>

      <!-- 输入区 -->
      <div style="margin-top: 15px; display: flex; gap: 10px;">
        <el-input v-model="userInput" placeholder="请输入你的问题..." @keyup.enter="sendMessage" clearable />
        <el-button type="primary" @click="sendMessage" :loading="loading">
          发送
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import MarkdownIt from "markdown-it";
import { getBaseURL } from '@/utils/request'

// 初始化 Markdown 渲染器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
});

const userInput = ref("");
const messages = ref([]);
const streamingContent = ref("");
const loading = ref(false);
let eventSource = null;

// 渲染 Markdown
const renderMarkdown = (text) => {
  return md.render(text || "");
};

const sendMessage = () => {
  if (!userInput.value.trim()) return;

  messages.value.push({ role: "user", content: userInput.value });
  loading.value = true;
  streamingContent.value = "";

  if (eventSource) {
    eventSource.close();
  }

  const url = getBaseURL() + `/sse/sse?userId=1&msg=${encodeURIComponent(
    userInput.value
  )}`;
  eventSource = new EventSource(url);

  eventSource.onmessage = (event) => {
    if (event.data === "[DONE]") {
      if (streamingContent.value) {
        messages.value.push({ role: "assistant", content: streamingContent.value });
      }
      streamingContent.value = "";
      loading.value = false;
      eventSource.close();
      return;
    }

    try {
      const json = JSON.parse(event.data);
      const delta = json?.choices?.[0]?.delta?.content;
      if (delta) {
        streamingContent.value += delta;
      }
    } catch (err) {
      console.error("解析 SSE 数据失败:", event.data);
    }
  };

  eventSource.onerror = (err) => {
    console.error("SSE 连接出错:", err);
    if (streamingContent.value) {
      messages.value.push({ role: "assistant", content: streamingContent.value });
    }
    streamingContent.value = "";
    loading.value = false;
    eventSource.close();
  };

  userInput.value = "";
};
</script>

<style scoped>
.el-card {
  border-radius: 10px;
}
</style>

<!-- GitHub 风格 Markdown 样式 -->
<style>
.markdown-body {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
  line-height: 1.6;
}

.markdown-body pre {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 6px;
  overflow-x: auto;
}

.markdown-body code {
  background-color: #f6f8fa;
  padding: 2px 4px;
  border-radius: 4px;
}
</style>
